const app = getApp<IAppOption>() as any
import { requestPUT, requestGET } from '../../utils/service'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageData: {} as any,
    arrSelectedIndex: -1,
    imgUrl: app.globalData.commonUrl,
    showCheckInfoModal: false,
    date: '',
    personInfo: wx.getStorageSync('userInfo'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getDetails(options.id)
    var now = new Date();
    var formattedDate = this.formatDate(now);
    this.setData({ date: formattedDate })
  },

  // 获取体检包详情
  getDetails(id: any) {
    requestGET("physicalexaminationpackage/getphysicalexaminationpackagesdetail", { physicalExaminationPackageId: id })
      .then((res: any) => {
        if (res.data.code == '200') {
          // 数据处理
          let response = res.data.data
          let vitamin = ''//维生素
          let traceElement = '' //微量元素
          let foodArrForShow = [] as AnyArray //最终要用来展示的食物对象数据

          let foodArr = [] as AnyArray //所有的食物合集
          let foodObj = {} as any //食物分类后的对象
          response.physicalExaminationPackageBasisList.forEach((item: any) => {
            if (item.nutritionAssessmentType == '维生素') {
              vitamin = vitamin ? vitamin + '、' + item.nutritionName : item.nutritionName
            } else if (item.nutritionAssessmentType == '微量元素') {
              traceElement = traceElement ? traceElement + '、' + item.nutritionName : item.nutritionName
            } else if (item.nutritionAssessmentType == '食物') {
              foodArr.push(item)
            }
          });
          // 格式化用来展示的食物对象数据
          foodArr.forEach((item: any) => {
            foodObj[item.foodGroup] = foodObj[item.foodGroup] ? foodObj[item.foodGroup] + '、' + item.nutritionName : item.nutritionName
          })
          for (let key in foodObj) {
            if (foodObj.hasOwnProperty(key)) { // 确保是对象自有属性，不是原型链上的属性
              foodArrForShow.push({
                title: key,
                content: foodObj[key]
              })
            }
          }
          let pageData = res.data.data
          pageData.vitamin = vitamin
          pageData.traceElement = traceElement
          pageData.foodArrForShow = foodArrForShow
          pageData.physicalExaminationPrecautions = (pageData.physicalExaminationPrecautions).split(';')
          this.setData({
            pageData: pageData
          })
          console.log(this.data.pageData);
        } else {
          wx.showToast({
            title: '服务异常',
            icon: 'error',
            duration: 2000
          })
        }
      })
  },

  // 展开折叠
  clickTab(e: any) {
    let index = -1
    if (e.currentTarget.dataset.index != this.data.arrSelectedIndex) {
      index = e.currentTarget.dataset.index
    }
    this.setData({
      arrSelectedIndex: index
    })
  },
  // 进入付款界面
  toPay() {
    console.log(wx.getStorageSync('logInStatus'))
    // 未注册
    if (wx.getStorageSync('logInStatus') == 'notRegister') {
      wx.showModal({
        title: '提示',
        content: '预约需要您先进行注册，是否去注册?',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/register/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    }
    this.setData({ showCheckInfoModal: true })
    // const url = "/pages/payPage/index?physicalExaminationPackageId="+this.data.pageData.physicalExaminationPackageId+'&physicalExaminationPackagePrice='+this.data.pageData.physicalExaminationPackagePrice+'&physicalExaminationLocation='+this.data.pageData.physicalExaminationLocation+'&physicalExaminationPackageTitle='+this.data.pageData.physicalExaminationPackageTitle
    // wx.navigateTo({
    //   url: url,
    // })
  },
  closeCheckInfo() {
    this.setData({ showCheckInfoModal: false })
  },
  onOkToPay() {
    wx.showLoading({
      title: '预约中,请稍后',
      mask: true
    })
    const params = {
      "physicalExaminationPackageId": this.data.pageData.physicalExaminationPackageId,
      "reservationDate": this.data.date,
    }
    requestPUT("reservation/reservePhysicalExaminationPackage", params)
      .then((res: any) => {
        wx.hideLoading()
        console.log(res)
        if (res.data.code == '200') {
          this.setData({ showCheckInfoModal: false })
          wx.navigateTo({
            url: '/pages/reservationOk/index?date=' + this.data.date + '&&physicalExaminationLocation=' + this.data.pageData.physicalExaminationLocation,
          })
        } else {
          wx.showToast({
            title: '预约失败',
            icon: 'error',
            duration: 2000
          })
        }
      })
  },
  // 格式化时间
  formatDate(date: any) {
    function padZero(num: any) {
      return num < 10 ? '0' + num : num;
    }
    var year = date.getFullYear();
    var month = padZero(date.getMonth() + 1);
    var day = padZero(date.getDate());
    // var hours = padZero(date.getHours());
    // var minutes = padZero(date.getMinutes());
    // var seconds = padZero(date.getSeconds());
    return `${year}-${month}-${day}`;
  }
})